package com.sumer.psychology.tag.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.sumer.psychology.tag.infrastructure.persistence.mongo.MongoTagRepository;

import java.util.HashMap;
import java.util.Map;

/**
 * 标签替换监听
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/30
 * Time: 9:13
 */
public class TagsReplacedEventListener extends ExchangeListener {
    private static final String BLOG_TAGS = "com.sumer.psychology.blog.domain.model.BlogTagsReplacedEvent";
    private static final String PHOTO_TAGS = "com.sumer.psychology.photo.domain.model.PhotoTagsReplacedEvent";
    private static final String SHARE_RESOURCE_TAGS = "com.sumer.psychology.sharing.domain.model.SharedResourceTagReplacedEvent";

    private static Map<String, String> tagMaps = new HashMap<>(3);

    static {
        tagMaps.put(BLOG_TAGS, "blog");
        tagMaps.put(PHOTO_TAGS, "photo");
        tagMaps.put(SHARE_RESOURCE_TAGS, "resource");
    }

    private static final String KEY = "Id.identity";
    private static final String PREFIX = "sumer_";

    private MongoTagRepository mongoTagRepository;

    public TagsReplacedEventListener(MongoTagRepository mongoTagRepository) {
        this.mongoTagRepository = mongoTagRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        mongoTagRepository().save(aTextMessage, tagMaps.get(aType));
        mongoTagRepository().replaceTags(
                aTextMessage,
                tagMaps.get(aType) + KEY,
                PREFIX + tagMaps.get(aType));
    }

    @Override
    protected String[] listensTo() {
        return new String[]{
                BLOG_TAGS,
                PHOTO_TAGS,
                SHARE_RESOURCE_TAGS};
    }

    private MongoTagRepository mongoTagRepository() {
        return mongoTagRepository;
    }
}
